{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import operator\n",
    "from os import listdir\n",
    "\n",
    "def img2vector(fileName):\n",
    "    returnVec = np.zeros((1,1024))\n",
    "    fr = open(fileName)\n",
    "    for i in range(32):\n",
    "        lineArr = fr.readline()\n",
    "        for j in range(32):\n",
    "            returnVec[0,32*i + j] = int(lineArr[j])\n",
    "    return returnVec"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 1.,\n",
       "       1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#testf\n",
    "testVec = img2vector('testDigits/0_13.txt')\n",
    "testVec[0,0:31]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def classify(inX, dataSet, labels, k):\n",
    "    dataSetSize = dataSet.shape[0]\n",
    "    diffMat = np.tile(inX,(dataSetSize,1)) - dataSet\n",
    "    sqDiffMat = diffMat ** 2\n",
    "    sqDistance = sqDiffMat.sum(axis = 1)\n",
    "    distance = sqDistance ** 0.5\n",
    "    sortAsDistance = distance.argsort()\n",
    "    classCount = {}\n",
    "    for i in range(k):\n",
    "        voteIlabel = labels[sortAsDistance[i]]\n",
    "        classCount[voteIlabel] = classCount.get(voteIlabel,0) +1\n",
    "    sortDeclassCount = sorted(classCount.items(),key=operator.itemgetter(1),reverse=True)\n",
    "    return sortDeclassCount[0][0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def handwritingClasstest():\n",
    "    hwLabels = []\n",
    "    trainingFileList = listdir('trainingDigits')\n",
    "    m = len(trainingFileList)\n",
    "    trainingMat = np.zeros((m,1024))\n",
    "    for i in range(m):\n",
    "        fileNameStr = trainingFileList[i]\n",
    "        fileStr = fileNameStr.split('.')[0]\n",
    "        classNumStr = int(fileStr.split('_')[0])\n",
    "        hwLabels.append(classNumStr)\n",
    "        trainingMat[i,:] = img2vector('trainingDigits/%s' % fileNameStr)\n",
    "    testFileList = listdir('testDigits')\n",
    "    errorCount = 0.0\n",
    "    mTest = len(testFileList)\n",
    "    wrongMat = []\n",
    "    k = 0\n",
    "    for i in range(mTest):\n",
    "        fileNameStr = testFileList[i]\n",
    "        fileStr = fileNameStr.split('.')[0]\n",
    "        classNumStr = int(fileStr.split('_')[0])\n",
    "        vecUnderTest = img2vector('testDigits/%s' % fileNameStr)\n",
    "        classifierResult = classify(vecUnderTest, trainingMat, hwLabels,3)\n",
    "        if classifierResult != classNumStr:\n",
    "            errorCount += 1.0\n",
    "            wrongMat.append([classifierResult,classNumStr])\n",
    "        \n",
    "        if i%int(mTest/10) ==0:\n",
    "            print(\"加载 %d%%\" % k)\n",
    "            k += 10\n",
    "    errorRate = errorCount/float(mTest)\n",
    "    print(\"\\n错误率：%.2f%%\" % errorRate)\n",
    "    print(\"\\n以下是预测错误的数据：\")\n",
    "    wrongMat = np.mat(wrongMat)\n",
    "    for i in range(len(wrongMat)):\n",
    "        print(\"(%d)预测值：%d , 真实值：%d\" % (i,wrongMat[i,0],wrongMat[i,1]))\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "加载 0%\n",
      "加载 10%\n",
      "加载 20%\n",
      "加载 30%\n",
      "加载 40%\n",
      "加载 50%\n",
      "加载 60%\n",
      "加载 70%\n",
      "加载 80%\n",
      "加载 90%\n",
      "加载 100%\n",
      "\n",
      "错误率：0.01%\n",
      "\n",
      "以下是预测错误的数据：\n",
      "(0)预测值：7 , 真实值：1\n",
      "(1)预测值：9 , 真实值：3\n",
      "(2)预测值：3 , 真实值：5\n",
      "(3)预测值：6 , 真实值：5\n",
      "(4)预测值：6 , 真实值：8\n",
      "(5)预测值：3 , 真实值：8\n",
      "(6)预测值：1 , 真实值：8\n",
      "(7)预测值：1 , 真实值：8\n",
      "(8)预测值：1 , 真实值：9\n",
      "(9)预测值：7 , 真实值：9\n"
     ]
    }
   ],
   "source": [
    "handwritingClasstest()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "完整代码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import operator\n",
    "from os import listdir\n",
    "\n",
    "def img2vector(fileName):\n",
    "    returnVec = np.zeros((1,1024))\n",
    "    fr = open(fileName)\n",
    "    for i in range(32):\n",
    "        lineArr = fr.readline()\n",
    "        for j in range(32):\n",
    "            returnVec[0,32*i + j] = int(lineArr[j])\n",
    "    return returnVec\n",
    "def classify(inX, dataSet, labels, k):\n",
    "    dataSetSize = dataSet.shape[0]\n",
    "    diffMat = np.tile(inX,(dataSetSize,1)) - dataSet\n",
    "    sqDiffMat = diffMat ** 2\n",
    "    sqDistance = sqDiffMat.sum(axis = 1)\n",
    "    distance = sqDistance ** 0.5\n",
    "    sortAsDistance = distance.argsort()\n",
    "    classCount = {}\n",
    "    for i in range(k):\n",
    "        voteIlabel = labels[sortAsDistance[i]]\n",
    "        classCount[voteIlabel] = classCount.get(voteIlabel,0) +1\n",
    "    sortDeclassCount = sorted(classCount.items(),key=operator.itemgetter(1),reverse=True)\n",
    "    return sortDeclassCount[0][0]\n",
    "def handwritingClasstest():\n",
    "    hwLabels = []\n",
    "    trainingFileList = listdir('trainingDigits')\n",
    "    m = len(trainingFileList)\n",
    "    trainingMat = np.zeros((m,1024))\n",
    "    for i in range(m):\n",
    "        fileNameStr = trainingFileList[i]\n",
    "        fileStr = fileNameStr.split('.')[0]\n",
    "        classNumStr = int(fileStr.split('_')[0])\n",
    "        hwLabels.append(classNumStr)\n",
    "        trainingMat[i,:] = img2vector('trainingDigits/%s' % fileNameStr)\n",
    "    testFileList = listdir('testDigits')\n",
    "    errorCount = 0.0\n",
    "    mTest = len(testFileList)\n",
    "    wrongMat = []\n",
    "    k = 0\n",
    "    for i in range(mTest):\n",
    "        fileNameStr = testFileList[i]\n",
    "        fileStr = fileNameStr.split('.')[0]\n",
    "        classNumStr = int(fileStr.split('_')[0])\n",
    "        vecUnderTest = img2vector('testDigits/%s' % fileNameStr)\n",
    "        classifierResult = classify(vecUnderTest, trainingMat, hwLabels,3)\n",
    "        if classifierResult != classNumStr:\n",
    "            errorCount += 1.0\n",
    "            wrongMat.append([classifierResult,classNumStr])\n",
    "        \n",
    "        if i%int(mTest/10) ==0:\n",
    "            print(\"加载 %d%%\" % k)\n",
    "            k += 10\n",
    "    errorRate = errorCount/float(mTest)\n",
    "    print(\"\\n错误率：%.2f%%\" % errorRate)\n",
    "    print(\"\\n以下是预测错误的数据：\")\n",
    "    wrongMat = np.mat(wrongMat)\n",
    "    for i in range(len(wrongMat)):\n",
    "        print(\"(%d)预测值：%d , 真实值：%d\" % (i,wrongMat[i,0],wrongMat[i,1]))\n",
    "handwritingClasstest()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
